package com.jn.mvvm2.views;

import android.os.Bundle;
import android.widget.SearchView;

import androidx.activity.viewModels;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.jn.mvvm2.R;
import com.jn.mvvm2.adapter.PetAdapter;
import com.jn.mvvm2.databinding.ActivityPetListBinding;
import com.jn.mvvm2.entity.Pet;
import com.jn.mvvm2.viewmodel.PetViewModel;

import java.util.List;

public class PetListActivity extends AppCompatActivity {
    private ActivityPetListBinding binding;
    private PetViewModel petViewModel;
    private PetAdapter petAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.pet_item);
        petViewModel = new ViewModelProvider(this).get(PetViewModel.class);
        binding.setPetViewModel(petViewModel);
        binding.setLifecycleOwner(this);

        initializeRecyclerView();
        setupSearchView();
        observePetList();
    }

    private void initializeRecyclerView() {
        petAdapter = new PetAdapter(R.layout.pet_item);
        RecyclerView recyclerView = binding.petRecyclerView;
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(petAdapter);
    }

    private void setupSearchView() {
        SearchView searchView = binding.searchView;
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                petViewModel.searchPets(newText);
                return true;
            }
        });
    }

    private void observePetList() {
        petViewModel.getPetList().observe(this, new Observer<List<Pet>>() {
            @Override
            public void onChanged(List<Pet> pets) {
                petAdapter.submitList(pets);
            }
        });
    }
}